package com.chenpp.redis.pubsub;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * @Description
 * @Author chenpp
 * @Date 2019/10/22 10:00
 */
public class Subscriber extends JedisPubSub {

    public void onMessage(String channel, String message) {
        System.out.println("订阅的channel:"+channel+"渠道，发布消息:"+message);
//        if(message.equals("English")){
//            this.unsubscribe(channel);
//        }
    }

    public void onPMessage(String pattern, String channel, String message) {
        System.out.println("订阅的pattern模式，对:"+channel+"渠道，发布消息:"+message);

    }

    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("订阅channel:"+channel+"渠道，subscribedChannels:"+subscribedChannels);

    }

    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("取消对channel:"+channel+"的订阅，subscribedChannels:"+subscribedChannels);

    }

    public void onPUnsubscribe(String pattern, int subscribedChannels) {
        System.out.println("取消pattern:"+pattern+"模式下的订阅，subscribedChannels:"+subscribedChannels);

    }

    public void onPSubscribe(String pattern, int subscribedChannels) {
        System.out.println("进行pattern:"+pattern+"模式下的订阅，subscribedChannels:"+subscribedChannels);

    }

    //客户端订阅频道
    //因为在订阅channel,该客户端的线程就会挂起？？ 不能再接收其他指令，故在redis客户端无法演示取消订阅
    //使用代码的话可以采取多线程的方法，在指定时间后取消订阅 通过JedisPubSub的unsubscribe方法
    //或者在监听的消息里 : 当监听到指定消息后取消订阅(更加可控)
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        final Subscriber subscriber = new Subscriber();

        Thread thread = new Thread( new Runnable() {
            public void run() {
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行取消订阅逻辑.......");
                subscriber.unsubscribe();
            }
        });
        thread.start();
        jedis.subscribe(subscriber, "course");//最终也是调用了JedisPubSub的subscribe方法

    }
}
